<template>
    <el-card>
        <template #header>
            <h3>预约挂号管理</h3>
        </template>
        <!-- 搜索区域 -->
        <el-form inline>
            <el-form-item label="居民" style="width: 200px">
                <el-input v-model="params.resident"></el-input>
            </el-form-item>
            <el-form-item label="医生" style="width: 200px">
                <el-input v-model="params.doctor"></el-input>
            </el-form-item>
            <el-form-item label="医疗机构" style="width: 250px">
                <el-autocomplete v-model="params.health_institution" value-key="name" :fetch-suggestions="querySearch"
                    clearable class="inline-input w-50" placeholder="" @select="handleSelect" @input="clear" />
            </el-form-item>
            <el-form-item label="时间" style="width: 200px">
                <el-date-picker v-model="params.date" type="date" placeholder="选择日期" style="width: 200px"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="params.status" placeholder="" style="width: 90px">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchAppointments()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="appointments" border @sort-change="handleSortChange">
            <el-table-column label="居民" prop="resident" sortable="custom" align="center" width="100"></el-table-column>
            <el-table-column label="身份证号" prop="id_card" sortable="custom" align="center" width="170">
                <template #default="scope">
                    <span>
                        <!-- 身份证号脱敏处理 -->
                        {{ scope.row.id_card.slice(0, 6) + '****' + scope.row.id_card.slice(scope.row.id_card.length -
                            4) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="电话" prop="phone" sortable="custom" align="center" width="120"></el-table-column>
            <el-table-column label="医生" prop="doctor" sortable="custom" align="center" width="100"></el-table-column>
            <el-table-column label="科室" prop="department" sortable="custom" align="center"></el-table-column>
            <el-table-column label="医疗机构" prop="health_institution" sortable="custom" align="center"
                width="180"></el-table-column>
            <el-table-column label="时间" prop="date" sortable="custom" align="center" width="180">
                <template #default="scope">
                    <span
                        v-text="scope.row.date + '&nbsp;&nbsp;' + scope.row.start_time.substring(0, 5) + '-' + scope.row.end_time.substring(0, 5)">
                    </span>
                </template>
            </el-table-column>

            <el-table-column label="状态" prop="status" sortable="custom" align="center" width="90">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == 0">待确认</el-tag>
                    <el-tag v-else-if="scope.row.status == 1" type="success">已确认</el-tag>
                    <el-tag v-else-if="scope.row.status == 2" type="warning">进行中</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160">
                <template #default="scope">
                    <div class="appointment">
                        <span>
                            <!-- 退回确认气泡 -->
                            <el-popconfirm width="250" icon-color="#626AEF" title="确认退回该预约挂号吗？">
                                <template #reference>
                                    <el-button type="danger">退回</el-button>
                                </template>
                                <template #actions="{ confirm, cancel }">
                                    <el-button size="small" @click.once="cancel">取消</el-button>
                                    <el-button type="danger" size="small"
                                        @click.once="callbackAppointment(scope.row, confirm)">
                                        确认
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </span>
                        <span v-if="scope.row.status == 0" class="confirm">
                            <el-button type="success" @click="confirmAppointment(scope.row)">
                                确认
                            </el-button>
                        </span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
</template>
<script>
import { appointmentsFindAPI, appointmentsStatusUpdateAPI, cancelAppointmentAPI } from '@/api/appointment';
import { ElMessage } from 'element-plus';
import { healthInstitutionFindAPI } from '@/api/healthInstitution';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                resident: '',
                doctor: '',
                department: '',
                health_institution: '',
                health_institution_id: '',
                date: '',
                role: JSON.parse(sessionStorage.getItem('user')).role,
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            appointments: [],
            healthInstitutions: [],
            statusOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '待确认'
                },
                {
                    value: '1',
                    label: '已确认'
                },
                {
                    value: '2',
                    label: '进行中'
                }
            ]
        }
    },
    methods: {
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadAppointmentsList();
        },
        searchAppointments() {
            this.handleCurrentChange(1);
        },
        loadAppointmentsList() {
            appointmentsFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.appointments = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            healthInstitutionFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.healthInstitutions = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        appointmentsStatusUpdate(row, confirm) {
            row.role = JSON.parse(sessionStorage.getItem('user')).role;
            appointmentsStatusUpdateAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadAppointmentsList();
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        callbackAppointment(row, confirm) {
            console.log(row);
            let appointParams = {};
            appointParams.tradeNo = "预约" + row.id;
            cancelAppointmentAPI(appointParams).then((resp) => {
                if (resp.data.code == 2000) {
                    this.showCancelWindow = false;
                    row.status = 1;
                    this.appointmentsStatusUpdate(row, confirm);
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            });
            if (confirm) {
                confirm();
            }
        },
        confirmAppointment(row, confirm) {
            // row.status = 0;
            this.appointmentsStatusUpdate(row);
        },
        //该方法选择列表后触发
        handleSelect(item) {
            this.params.health_institution_id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearch(queryString, cb) {
            let results = this.healthInstitutions;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilter(queryString) {
            return (healthInstitutions) => {
                // 确保 healthInstitutions 是一个字符串或对象
                if (typeof healthInstitutions === 'object') {
                    return JSON.stringify(healthInstitutions).toLowerCase().indexOf(queryString.toLowerCase()) > -1;
                }
                return healthInstitutions.toLowerCase().indexOf(queryString.toLowerCase()) > -1;
            };
        },
        //点击清除按钮时触发事件
        clear() {
            this.params.health_institution_id = '';
            this.loadAppointmentsList();
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                appointmentsFindAPI(this.params).then((resp) => {
                    if (resp.data.code == 2000) {
                        this.appointments = resp.data.datas;
                        this.params.total = resp.data.total;
                    } else {
                        ElMessage.error(resp.data.message);
                    }
                })
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                appointmentsFindAPI(this.params).then((resp) => {
                    if (resp.data.code == 2000) {
                        this.appointments = resp.data.datas;
                        this.params.total = resp.data.total;
                    } else {
                        ElMessage.error(resp.data.message);
                    }
                })
            }
        }
    },
    created() {
        this.loadAppointmentsList();
    }
}
</script>

<style scoped>
.example-pagination-block {
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.description {
    margin: 0px 15px;
}

.appointment {
    display: flex;
    align-items: center;
}

.appointment .confirm {
    margin-left: 10px;
}

.title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>